import { plugin, Messagetype, segment } from 'alemon'
import { existsSync, readFileSync } from 'fs'
import { join } from 'path'
import { MyDirPath } from '../../app.config.js'
import lodash from 'lodash'
import dayjs from '../../lib/day.js'
import axios from 'axios'
import cache from '../../db/cache/cache.js'
export class K_查询天气 extends plugin {
  constructor() {
    super({
      dsc: '查询天气',
      rule: [
        {
          reg: '^/查询天气(.*)$',
          fnc: '查询天气'
        }
      ]
    })
  }
  async 查询天气(e: Messagetype): Promise<boolean> {
    const tqPath = join(MyDirPath, '/resources/data/查询天气')
    const cityJson = join(tqPath, '最新_city.json')
    if (!existsSync(cityJson)) {
      return e.reply('找不到city内容')
    }

    const cityList = JSON.parse(readFileSync(cityJson, 'utf-8'))

    const city = e.cmd_msg

      .replace('/查询天气', '')
      .replace(/(市|区|县|省)$/, '')
      .trim()
    // console.log(city)

    if ((city ?? '') === '') {
      return e.reply('查询城市不能为空')
    }
    // 查询城市city_code
    const cityData = lodash.filter(cityList, item => {
      return lodash.includes(item.city_name, city)
    })

    if (cityData.length !== 0 && cityData[0].city_code !== '') {
      // 读取缓存
      const data: string | null = await cache.get(`wea:${cityData[0].city_code}`)

      if (data) {
        await e.reply(
          '',
          segment.embed(
            ...(JSON.parse(data) as [title: string, prompt: string, url: string, arr: any[]])
          )
        )

        return true
      }
      // console.log(`http://t.weather.itboy.net/api/weather/city/${cityData[0].city_code}`)

      const { data: wea } = await axios
        .get(`http://t.weather.itboy.net/api/weather/city/${cityData[0].city_code}`)
        .catch(err => err)
      if (!wea || wea.status !== 200) {
        return e.reply('天气查询失败')
      }

      let weather_icon: string
      const now = dayjs() // 获取当前时间
      const start = dayjs().hour(18).minute(0).second(0) // 晚上6点
      const end = dayjs().add(1, 'day').hour(6).minute(0).second(0) // 第二天早上6点

      if (wea.data.forecast[0].type === '晴') {
        if (now.isBetween(start, end)) {
          //   console.log('当前时间在晚上6点到早上6点之间');
          weather_icon =
            'https://ghproxy.com/https://raw.githubusercontent.com/kongxiangyiren/305-wea-ico/master/天气/夜晴.png'
        } else {
          //   console.log('当前时间不在晚上6点到早上6点之间');
          weather_icon =
            'https://ghproxy.com/https://raw.githubusercontent.com/kongxiangyiren/305-wea-ico/master/天气/日晴.png'
        }
      } else if (wea.data.forecast[0].type === '多云') {
        if (now.isBetween(start, end)) {
          //   console.log('当前时间在晚上6点到早上6点之间');
          weather_icon =
            'https://ghproxy.com/https://raw.githubusercontent.com/kongxiangyiren/305-wea-ico/master/天气/夜间多云.png'
        } else {
          //   console.log('当前时间不在晚上6点到早上6点之间');
          weather_icon =
            'https://ghproxy.com/https://raw.githubusercontent.com/kongxiangyiren/305-wea-ico/master/天气/日间多云.png'
        }
      } else {
        if (existsSync(join(tqPath, `/天气/${wea.data.forecast[0].type}.png`))) {
          weather_icon = `https://ghproxy.com/https://raw.githubusercontent.com/kongxiangyiren/305-wea-ico/master/天气/${wea.data.forecast[0].type}.png`
        } else {
          weather_icon =
            'https://ghproxy.com/https://raw.githubusercontent.com/kongxiangyiren/305-wea-ico/master/天气/无.png'
        }
      }

      const embedContent = [
        `${wea.cityInfo.city} ${wea.data.forecast[0].type}`,
        '',
        weather_icon,
        [
          `${wea.data.forecast[0].ymd} ${wea.data.forecast[0].week}`,
          `当前温度区间：${wea.data.forecast[0].high}/${wea.data.forecast[0].low}`,
          // `最高温度：${wea.data.forecast[0].high}`,
          // `最低温度：${wea.data.forecast[0].low}`,
          `当前湿度：${wea.data.shidu}`,
          `日出：${wea.data.forecast[0].sunrise}`,
          `日落：${wea.data.forecast[0].sunset}`,
          `风向：${wea.data.forecast[0].fx}`,
          `风力：${wea.data.forecast[0].fl}`
        ]
      ] as [title: string, prompt: string, url: string, arr: any[]]
      // 缓存10分钟
      cache.set(`wea:${cityData[0].city_code}`, JSON.stringify(embedContent), 10 * 60) // 设置key的过期时间为10分钟

      await e.reply('', segment.embed(...embedContent))
      return true
    } else {
      return e.reply('没有对应城市的天气信息')
    }
  }
}
